<template>
  <div class="flex">
    <ContentDetailWrap :title="t('warehouse.add')" class="w-70% inline-block">
      <template #header>
        <BaseButton @click="go(-1)">
          {{ t('common.back') }}
        </BaseButton>
        <BaseButton type="primary" @click="submit(formRef)">
          {{ t('action.save') }}
        </BaseButton>
      </template>
      <!--    表单-->
      <el-form class="flex flex-wrap form-container" :model="form" ref="formRef" label-width="25%">
        <el-form-item
          :label="t('discount.discount_category')"
          class="w-50%"
          prop="discount_category"
          required
        >
          <el-select
            v-model="form.discount_category"
            :filterable="true"
            :placeholder="t('discount.discount_category')"
            :clearable="false"
            :multiple="false"
            @change="handleAppliesProduct"
          >
            <el-option
              v-for="item in discountCategoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('discount.code_title')" class="w-50%" prop="code_title" required>
          <div class="w-full flex items-center">
            <el-input
              v-model="form.code_title"
              :placeholder="'请输入' + t('discount.code_title')"
            />
            <el-button type="primary" @click="generateCode" class="ml-2">生成随机券码</el-button>
          </div>
        </el-form-item>
        <el-form-item
          :label="t('discount.discount_type')"
          class="w-50%"
          prop="discount_type"
          required
        >
          <el-select
            v-model="form.discount_type"
            :filterable="true"
            :placeholder="t('discount.discount_type')"
            :clearable="false"
            :multiple="false"
          >
            <el-option
              v-for="item in discountTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('discount.discount_value')"
          class="w-50%"
          prop="discount_value"
          required
        >
          <el-input-number
            v-model="form.discount_value"
            :placeholder="'请输入' + t('discount.discount_value')"
            :precision="2"
            :step="0.01"
            :min="0"
          />
        </el-form-item>
        <el-form-item
          :label="t('discount.applies_to_type')"
          class="w-50%"
          prop="applies_to_type"
          v-if="isShowApplies"
        >
          <el-select
            v-model="form.applies_to_type"
            :filterable="true"
            :placeholder="t('discount.applies_to_type')"
            :clearable="false"
            :multiple="false"
            @change="changeApppliesData"
          >
            <el-option
              v-for="item in appliesToTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('discount.applies_to_value')"
          class="w-50%"
          prop="applies_to_value"
          v-if="isShowApplies"
        >
          <div class="w-full flex items-center">
            <el-select-v2
              v-model="form.applies_to_value"
              :options="salesPidsOptions"
              :placeholder="'请选择' + t('discount.applies_to_value')"
              multiple
              clearable
              filterable
              :props="{ label: dataSources == 1 ? 'productname' : 'cname', value: 'id' }"
              @change="handleSalesPidsChange"
            />
            <el-button type="primary" @click="handleOpenSalesPids" class="ml-2">选择</el-button>
          </div>
        </el-form-item>

        <!--最低购买值-->
        <el-form-item
          :label="t('discount.min_purchase_req_type')"
          class="w-50%"
          prop="min_purchase_req_type"
          required
        >
          <el-select
            v-model="form.min_purchase_req_type"
            :filterable="true"
            :placeholder="t('discount.min_purchase_req_type')"
            :clearable="false"
            :multiple="false"
            @change="changeminPurchase"
          >
            <el-option
              v-for="item in minPurchaseTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('discount.min_purchase_req_value')"
          class="w-50%"
          prop="min_purchase_req_value"
        >
          <el-input-number
            v-model="form.min_purchase_req_value"
            :disabled="!isShowMinPurchase"
            :precision="2"
            :min="1"
          />
        </el-form-item>

        <!--资格-->
        <el-form-item
          :label="t('discount.eligibility_type')"
          class="w-50%"
          prop="eligibility_type"
          required
        >
          <el-select
            v-model="form.eligibility_type"
            :filterable="true"
            :placeholder="t('discount.eligibility_type')"
            :clearable="false"
            :multiple="false"
            @change="changeEligibilityData"
          >
            <el-option
              v-for="item in eligibilityTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="t('discount.eligibility_value')"
          class="w-50%"
          prop="eligibility_value"
        >
          <div class="w-full flex items-center">
            <el-select-v2
              v-model="form.eligibility_value"
              :options="eligibilityOptions"
              :placeholder="'请选择' + t('discount.eligibility_value')"
              multiple
              clearable
              filterable
              :props="{ label: 'cusname', value: 'id' }"
              @change="handleEligibilityChange"
            />
            <el-button
              type="primary"
              @click="handleOpenEligibility"
              :disabled="!isShowEligibility"
              class="ml-2"
              >选择</el-button
            >
          </div>
        </el-form-item>

        <el-form-item
          :label="t('discount.max_discount_uses_type')"
          class="w-50%"
          prop="max_discount_uses_type"
        >
          <el-select
            v-model="form.max_discount_uses_type"
            :filterable="true"
            :placeholder="t('discount.max_discount_uses_type')"
            :clearable="false"
            :multiple="true"
            @change="handleMaxUses"
          >
            <el-option
              v-for="item in maxUseTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!isShowMaxUse"
          :label="t('discount.max_discount_uses_value')"
          class="w-50%"
          prop="max_discount_uses_value"
          required
        >
          <el-input-number v-model="form.max_discount_uses_value" :min="1" />
        </el-form-item>

        <!-- 有效期 -->
        <el-form-item
          :label="t('discount.activedate_start')"
          class="w-50%"
          prop="activedate_start"
          required
        >
          <el-date-picker
            v-model="form.activedate_start"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            :placeholder="'请输入' + t('discount.activedate_start')"
          />
        </el-form-item>
        <el-form-item :label="t('discount.activedate_end')" class="w-50%" prop="activedate_end">
          <el-date-picker
            v-model="form.activedate_end"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            :placeholder="'请输入' + t('discount.activedate_end')"
          />
        </el-form-item>
      </el-form>
    </ContentDetailWrap>

    <ContentDetailWrap :title="t('warehouse.add')" class="w-30% inline-block">
      <template #header>
        <b>优惠券信息汇总:</b>
        <p></p>
      </template>
      <div>
        <p>{{ form.code_title }}</p>
        <b>类型</b>
        <p>{{ form.discount_category == 1 ? '商品' : '订单' }}降价金额</p>
        <b>详细信息</b>

        <ul class="data-list">
          <li>适用于在线商店</li>
          <li>{{
            form.discount_type == 1
              ? '订单' + form.discount_value + '%折扣'
              : '订单立减' + form.discount_value
          }}</li>
          <li>{{
            form.min_purchase_req_type == 1
              ? '无最低购买要求'
              : form.min_purchase_req_type == 2
                ? '最低购买' + form.min_purchase_req_value
                : '最低购买' + form.min_purchase_req_value + '件'
          }}</li>
          <li>{{ form.eligibility_type == 1 ? '全部客户' : '指定客户' }}</li>
          <li>
            <ol>
              <li v-for="(iterm, index) in form.max_discount_uses_type" :key="index">
                {{
                  iterm == 1 ? '最多使用' + form.max_discount_uses_value + '次' : '每人只能使用一次'
                }}
              </li>
            </ol>
          </li>
          <li
            >有效期：从{{ form.activedate_start }}
            {{ form.activedate_end ? ' ~ ' + form.activedate_end : '至今' }}</li
          >
        </ul>
        <b>绩效</b>
        <ul class="data-list">
          <li>已使用{{ orderTotal?.total }}次</li>
          <li>总销售额：{{ orderTotal?.sum }}</li>
        </ul>
      </div>
    </ContentDetailWrap>
  </div>
  <!--  选择聚合商品的组合售卖SKU商品弹框-->
  <PrimarPidDialog
    ref="DialogSalesPidsCheckedRef"
    @expose-multiple-data="getExposeSalesPidsData"
    :multiple="true"
  />
  <Customer
    ref="DialogEligibilityRef"
    @expose-multiple-data="getExposeEligibilityData"
    :multiple="true"
  />
</template>
<script setup lang="ts">
import PrimarPidDialog from '@/components/Dialog/src/Discount.vue'
import Customer from '@/components/Dialog/src/Customer/Index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'

import { ElMessage, ElMessageBox, ElLoading, type FormRules, type FormInstance } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { getFieldEnumApi, saveDataApi, getInfoApi, getOrderDiscountInfoApi } from '@/api/discount'

const { push, go } = useRouter()
const route = useRoute()
const { t } = useI18n()
const form = ref<Record<string, any>>({
  discount_category: '',
  code_title: '',
  discount_type: '',
  discount_value: '',
  applies_to_type: '',
  applies_to_value: []
})
const formRef = ref<FormInstance>()
//整单打折不需要选择商品
const isShowApplies = ref<boolean>(false)
const isShowEligibility = ref<boolean>(false)
const isShowMinPurchase = ref<boolean>(true)
const isShowMaxUse = ref<boolean>(true)
const handleAppliesProduct = (val: number) => {
  if (val == 2) {
    isShowApplies.value = false
    form.value.applies_to_type = ''
    form.value.applies_to_value = ''
    salesPidsOptions.value = []
  } else {
    isShowApplies.value = true
  }
}
const changeminPurchase = (val: number) => {
  if (val == 1) {
    isShowMinPurchase.value = false
  } else {
    isShowMinPurchase.value = true
  }
  form.value.min_purchase_req_value = ''
}
const handleMaxUses = (val) => {
  if (val.includes(1)) {
    isShowMaxUse.value = false
  } else {
    isShowMaxUse.value = true
    form.value.max_discount_uses_value = ''
  }
}
const salesPidsOptions = ref<any[]>([]) // 聚合商品的组合售卖SKU商品
const eligibilityOptions = ref<any[]>([]) //
const orderTotal = ref<any>() //

const discountCategoryList = ref<any[]>([])
const discountTypeList = ref<any[]>([])
const appliesToTypeList = ref<any[]>([])
const minPurchaseTypeList = ref<any[]>([])
const eligibilityTypeList = ref<any[]>([])
const maxUseTypeList = ref<any[]>([])
const dataSources = ref<number>(1)
const changeApppliesData = (val: number) => {
  dataSources.value = val
  form.value.applies_to_value = ''
  salesPidsOptions.value = []
}

const changeEligibilityData = (val: number) => {
  if (val == 1) {
    isShowEligibility.value = false
  } else if (val == 3) {
    isShowEligibility.value = true
  }
  form.value.eligibility_value = ''
  eligibilityOptions.value = []
}
// 响应式数据

// 字符池配置（可扩展）
const CHAR_POOL = {
  uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  lowercase: 'abcdefghijklmnopqrstuvwxyz',
  numbers: '0123456789'
}

// 生成随机长度（6-10）
const getRandomLength = () => Math.floor(Math.random() * 5) + 6

// 核心生成逻辑
const generateCouponCode = () => {
  // 合并字符池
  const chars = Object.values(CHAR_POOL).join('')
  const length = getRandomLength()

  // 使用更安全的随机方法
  const randomValues = new Uint32Array(length)
  window.crypto.getRandomValues(randomValues)

  let code = ''
  for (let i = 0; i < length; i++) {
    code += chars[randomValues[i] % chars.length]
  }

  return code
}

// 生成按钮处理
const generateCode = () => {
  form.value.code_title = generateCouponCode()
}
//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getFieldEnumApi({ field: 'all' })
  discountCategoryList.value = resp.data.discount_category
  discountTypeList.value = resp.data.discount_type
  appliesToTypeList.value = resp.data.applies_to_type
  minPurchaseTypeList.value = resp.data.min_purchase_req_type
  eligibilityTypeList.value = resp.data.eligibility_type
  maxUseTypeList.value = resp.data.max_discount_uses_type
}

// 聚合商品的组合售卖SKU商品弹框 组件方法 start
const DialogSalesPidsCheckedRef = ref<InstanceType<typeof PrimarPidDialog>>()

const handleOpenSalesPids = () => {
  nextTick(() => {
    if (!DialogSalesPidsCheckedRef.value) return
    DialogSalesPidsCheckedRef.value.dataSources = dataSources.value
    DialogSalesPidsCheckedRef.value.dialogVisible = true

    DialogSalesPidsCheckedRef.value.initialize(
      form.value.applies_to_value
        ? form.value.applies_to_value.map((item: any) => ({ id: item }))
        : []
    )
  })
}

const getExposeSalesPidsData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.applies_to_value && form.value.applies_to_value !== val[0].id) {
  }
  salesPidsOptions.value = val
  nextTick(() => {
    form.value.applies_to_value = val.map((item: any) => item.id)
  })
}

const handleSalesPidsChange = (val: number[]) => {
  form.value.applies_to_value = val
}
// 聚合商品的组合售卖SKU商品弹框 组件方法 end

// 购买资格用户弹框 组件方法 start
const DialogEligibilityRef = ref<InstanceType<typeof Customer>>()

const handleOpenEligibility = () => {
  nextTick(() => {
    if (!DialogEligibilityRef.value) return
    DialogEligibilityRef.value.dialogVisible = true

    DialogEligibilityRef.value.initialize(
      form.value.eligibility_value
        ? form.value.eligibility_value.map((item: any) => ({ id: item }))
        : []
    )
  })
}

const getExposeEligibilityData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.eligibility_value && form.value.eligibility_value !== val[0].id) {
  }
  eligibilityOptions.value = val
  nextTick(() => {
    form.value.eligibility_value = val.map((item: any) => item.id)
  })
}

const handleEligibilityChange = (val: number[]) => {
  form.value.eligibility_value = val
}
// 购买资格用户弹框 组件方法 end

const state = reactive({
  source: route.query.source ? decodeURIComponent(route.query.source as string) : ''
})
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const params = { ...form.value } as unknown as Record<string, any>
      console.log(params, 123)
      if (params.applies_to_value && Array.isArray(params.applies_to_value)) {
        params.applies_to_value = params.applies_to_value.join(',')
      }
      if (params.max_discount_uses_type && Array.isArray(params.max_discount_uses_type)) {
        params.max_discount_uses_type = params.max_discount_uses_type.join(',')
      }
      if (params.eligibility_value && Array.isArray(params.eligibility_value)) {
        params.eligibility_value = params.eligibility_value.join(',')
      }
      const resp = await saveDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('discount.updateSucMsg'))
        if (state.source) {
          push(`${state.source}`)
        } else {
          push('/oaperations/discount')
        }
      }
    }
  })
}

const getDet = async () => {
  const resp = await getInfoApi(route.query.id as string)
  const respOrder = await getOrderDiscountInfoApi(route.query.id as string)
  eligibilityOptions.value =
    resp.data.clist?.map((item) => ({
      id: Number(item.id),
      cusname: item.name
    })) || []
  if (resp.data.applies_to_type == 1) {
    dataSources.value = 1
    salesPidsOptions.value =
      resp.data.plist?.map((item) => ({
        id: Number(item.id),
        productname: item.name
      })) || []
  }
  if (resp.data.applies_to_type == 2) {
    dataSources.value = 2
    salesPidsOptions.value =
      resp.data.plist?.map((item) => ({
        id: Number(item.id),
        cname: item.name
      })) || []
  }
  if (resp.data.max_discount_uses_type) {
    resp.data.max_discount_uses_type = resp.data.max_discount_uses_type
      .split(',')
      .map((m) => Number(m))
  }
  if (resp.data.applies_to_value) {
    resp.data.applies_to_value = resp.data.applies_to_value.split(',').map((m) => Number(m))
  }
  if (resp.data.eligibility_value) {
    resp.data.eligibility_value = resp.data.eligibility_value.split(',').map((m) => Number(m))
  }

  // 最后 nextTick 赋值 v-model
  await nextTick()
  form.value = resp.data
  orderTotal.value = respOrder.data
  if (resp.data.eligibility_type == 3) {
    isShowEligibility.value = true
  }
  if (resp.data.min_purchase_req_type == 1) {
    isShowMinPurchase.value = false
  }
  if (resp.data.discount_category == 1) {
    isShowApplies.value = true
  }
  if (resp.data.max_discount_uses_type.includes(1)) {
    isShowMaxUse.value = false
  }
}

onMounted(() => {
  getDropDownBoxInfo()
  getDet()
})
</script>

<style lang="less" scoped>
.form-container {
  align-items: flex-start;

  :deep(.el-form-item__label) {
    display: inline-block;
    width: 100%; /* 继承label-width的宽度 */
    overflow: hidden; /* 隐藏溢出内容 */
    text-align: right;
    text-overflow: ellipsis; /* 显示省略号 */
    white-space: nowrap; /* 禁止换行 */
  }
}
</style>
